package com.hframe.filter;

import com.hframe.FrameInit;
import org.apache.log4j.Logger;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;


public class PageSkipFilter implements Filter {
    private static Logger log = Logger.getLogger(PageSkipFilter.class);
    public static String SkipTag = "SkipTag" + PageSkipFilter.class.getName();

    public PageSkipFilter() {
    }

    @Override
    public void destroy() {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        String url = ((HttpServletRequest) request).getServletPath();
        if (null != request.getAttribute(SkipTag)) {
            chain.doFilter(request, response);
            return;
        }

        String srcUrl = url;
        int index = url.lastIndexOf(".");
        if (index > -1)
            url = url.substring(0, index);

        if (isUrlServlet(request, url)) {
            request.setAttribute(SkipTag, srcUrl);
            request.getRequestDispatcher(url).forward(request, response);
        } else {
            chain.doFilter(request, response);
        }
    }

    @Override
    public void init(FilterConfig fConfig) throws ServletException {
    }

    public boolean isUrlServlet(ServletRequest request, String url) {
        for (String item : FrameInit.getServleturls()) {
            if (url.equals(item))
                return true;

        }
        return false;
    }

}
